import time
from multiprocessing import Pool


def f(x):
    return x * x


def need_time_fun(x):
    time.sleep(1)
    return x * x


if __name__ == "__main__":
    with Pool() as pool:
        # apply 同步执行
        ret = pool.apply(need_time_fun, (2,))
        print("apply 同步: ", ret)
        # apply_async 异步执行
        ret = pool.apply_async(need_time_fun, (2,))
        print("apply_aynsc 异步:", ret.get(timeout=5))

        # map 并发同步执行
        ret = pool.map(need_time_fun, [1, 2, 3, 4])
        print("map 并发同步执行:", ret)

        # map_async
        ret = pool.map_async(need_time_fun, [1, 2, 3, 4])
        print("map_async 并发异步执行:", ret.get(timeout=5))

        # imap 分步执行
        it = pool.imap(need_time_fun, range(10))
        for i in range(10):
            print("imap ", next(it))
            # it.next(timeout=2)

        # imap_unordered 并发异步执行
        it_unord = pool.imap_unordered(need_time_fun, range(10))
        for i in range(10):
            print("imap_unordered ", next(it_unord))
            # it_unord.next(timeout=2)

""" 结果:
apply 同步:  4
apply_aynsc 异步: 4
map 并发同步执行: [1, 4, 9, 16]
map_async 并发异步执行: [1, 4, 9, 16]
imap  0
imap  1
imap  4
imap  9
imap  16
imap  25
imap  36
imap  49
imap  64
imap  81
imap_unordered  0
imap_unordered  1
imap_unordered  49
imap_unordered  16
imap_unordered  25
imap_unordered  4
imap_unordered  36
imap_unordered  9
imap_unordered  64
imap_unordered  81
"""